<script setup>
import { ref, nextTick } from 'vue'
import { artGetDetailService, artPublishService, artEditService } from '@/api/article'
import { Plus } from '@element-plus/icons-vue'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css';
import { baseURL } from '@/util/request';
import { imageUrlToFile } from '@/util/urlToFile'
// 绑定数据
const defaultForm = {
  title: '',
  cate_id: '',
  cover_img: '',
  content: '',
  state: ''
}
const quillEditorRef = ref()
const formModel = ref(defaultForm)
// 显示抽屉
const visibleDrawer = ref(false)
const open = async (row) => {
  visibleDrawer.value = true
  //更具是否编辑重置内容
  if (row.id) {
    const res = await artGetDetailService(row.id)
    formModel.value = res.data
    imgUrl.value = baseURL + res.data.cover_img
    // 提交给后台，需要的是 file 格式的，将网络图片，转成 file 格式
    // 网络图片转成 file 对象, 需要转换一下 添加和修改不是一个接口, 修改需要file格式，添加不需要
    formModel.value.cover_img = await imageUrlToFile(imgUrl.value, formModel.value.cover_img)
    console.log(formModel.value.cover_img)
  } else {
    await nextTick(() => {
      formModel.value = defaultForm
      imgUrl.value = ''
      quillEditorRef.value.setHTML('')
    })
  }

}
defineExpose({
  open
})

// 图片预览
const imgUrl = ref('')
const onUploadFile = (uploadFile) => {
  imgUrl.value = URL.createObjectURL(uploadFile.raw)
  formModel.value.cover_img = uploadFile.raw
}

// 发布/草稿文章
const emit = defineEmits(['success'])
const onPublish = async (state) => {
  // 将已发布还是草稿状态，存入 state
  formModel.value.state = state

  // 转换 formData 数据
  const fd = new FormData()
  for (let key in formModel.value) {
    fd.append(key, formModel.value[key])
  }
  // 编辑
  if (formModel.value.id) {
    console.log('编辑操作')
    await artEditService(fd)
    ElMessage.success('编辑成功')
    visibleDrawer.value = false
    emit('success', 'edit')
  } else { // 添加
    await artPublishService(fd)
    if (formModel.value.state === '草稿') {
      ElMessage.success('保存成功')
    } else {
      ElMessage.success('发布成功')
    }

    visibleDrawer.value = false
    emit('success', 'add')
  }
}


</script>

<template>
  <!-- 抽屉 -->
  <el-drawer v-model="visibleDrawer" :title="formModel.id ? '编辑文章' : '添加文章'" direction="rtl" size="50%">
    <!-- 发表文章表单 -->
    <el-form :model="formModel" ref="formRef" label-width="100px">
      <el-form-item label="文章标题" prop="title">
        <el-input v-model="formModel.title" placeholder="请输入标题"></el-input>
      </el-form-item>
      <el-form-item label="文章分类" prop="cate_id">
        <channel-select v-model="formModel.cate_id" width="100%"></channel-select>
      </el-form-item>
      <el-form-item label="文章封面" prop="cover_img">
        <el-upload class="avatar-uploader" :auto-upload="false" :show-file-list="false" :on-change="onUploadFile">
          <img v-if="imgUrl" :src="imgUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="文章内容" prop="content" class="editor_container">
        <div class="editor">
          <QuillEditor ref="quillEditorRef" placeholder="发生什么事了..." theme="snow" toolbar="full"
            v-model:content="formModel.content" content-type="html">
          </QuillEditor>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onPublish('已发布')">发布</el-button>
        <el-button type="info" @click="onPublish('草稿')">草稿</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>
<style lang="scss" scoped>
// 图片预览css 直接抄官网
.avatar-uploader {
  :deep() {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }

    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }

    .el-upload:hover {
      border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}

.editor {

  :deep(.ql-editor) {
    min-height: 200px;
    max-height: 400px;
  }
}
</style>
